/**
 * 
 */
package com.app.framework.context;

import com.app.framework.orm.session.PersistenceSession;
import com.app.framework.orm.session.SessionFactory;
import com.app.framework.result.RequestResult;

/**
 * @author lisong
 * @version 2013-2-28 下午5:18:38
 */
public abstract class AbstractContext implements Context {

	protected Response<?> response;
	
	protected PersistenceSession perssistenceSession;
	
	protected int transportProtocol;
	
	public AbstractContext(Response<?> response,int transportProtocol) {
		this.response = response;
		perssistenceSession = SessionFactory.openSession();
		this.transportProtocol = transportProtocol;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void execute() throws Exception {

		 RequestResult result = doExecute();

		response.setRequestResult(result);
		
		response.output();
		
		response.close();
		
		perssistenceSession.flush();//保存数据
	}
	
	protected abstract <T> RequestResult<T> doExecute() throws Exception;
	
	@Override
	public byte[] getContent() {
		
		return response.getRequest().getContent();
	}

	public Request getRequest() {
		return response.getRequest();
	}

	public PersistenceSession getPerssistenceSession() {
		return perssistenceSession;
	}

	@Override
	public int getTransportProtocol() {

		return transportProtocol;
	}
	
	public void close() {
		response = null;
		perssistenceSession.close();
		perssistenceSession = null;
	}
}
